import ivcs from '../ivcs-sdk';
const IRtc = ivcs.IRtc;
var arraytool = {
	/*删除数组中某一个元素*/
	removeAaary(_arr, _obj) {
		if (_arr) {
			var length = _arr.length;
			for (let i = 0; i < length; i++) {
				if (_arr[i] == _obj) {
					if (i == 0) {
						_arr.shift(); //删除并返回数组的第一个元素
						return _arr;
					} else if (i == length - 1) {
						_arr.pop(); //删除并返回数组的最后一个元素
						return _arr;
					} else {
						_arr.splice(i, 1); //删除下标为i的元素
						return _arr;
					}
				}
			}
		}
		return [];
	},

	/*删除数组中某一个id相同的元素*/
	removeArraybyid(_arr, _obj) {
		if (_arr) {
			var length = _arr.length;
			for (let i = 0; i < length; i++) {
				if (_arr[i].id == _obj.id) {
					if (i == 0) {
						_arr.shift(); //删除并返回数组的第一个元素
						return _arr;
					} else if (i == length - 1) {
						_arr.pop(); //删除并返回数组的最后一个元素
						return _arr;
					} else {
						_arr.splice(i, 1); //删除下标为i的元素
						return _arr;
					}
				}
			}
		}
		return _arr;
	},

	/*删除数组中某一个id相同的元素*/
	removeArrayWithid(_arr, id) {
		if (_arr) {
			var length = _arr.length;
			for (let i = 0; i < length; i++) {
				if (_arr[i].id === id) {
					if (i == 0) {
						_arr.shift(); //删除并返回数组的第一个元素
						return _arr;
					} else if (i == length - 1) {
						_arr.pop(); //删除并返回数组的最后一个元素
						return _arr;
					} else {
						_arr.splice(i, 1); //删除下标为i的元素
						return _arr;
					}
				}
			}
		}
		return _arr;
	},

	removewithoriginid(_arr, id) {
		if (_arr) {
			var length = _arr.length;
			for (let i = 0; i < length; i++) {
				if (_arr[i].originId === id) {
					if (i == 0) {
						_arr.shift(); //删除并返回数组的第一个元素
						return _arr;
					} else if (i == length - 1) {
						_arr.pop(); //删除并返回数组的最后一个元素
						return _arr;
					} else {
						_arr.splice(i, 1); //删除下标为i的元素
						return _arr;
					}
				}
			}
		}
		return _arr;
	},

	/*删除数组中某一个id相同的元素*/
	removeArraybyRoomid(_arr, _obj) {
		if (_arr) {
			var length = _arr.length;
			for (var i = 0; i < length; i++) {
				if (_arr[i].roomId == _obj.roomId) {
					if (i == 0) {
						_arr.shift(); //删除并返回数组的第一个元素
						return _arr;
					} else if (i == length - 1) {
						_arr.pop(); //删除并返回数组的最后一个元素
						return _arr;
					} else {
						_arr.splice(i, 1); //删除下标为i的元素
						return _arr;
					}
				}
			}
		}
		return _arr;
	},

	/*给数组中的元素根据id 添加一个新属性并返回*/
	addArrayPropByid(arr, prop, obj, propvalue) {
		if (arr) {
			arr.forEach(function(value) {
				if (value.id == obj.id) {
					value[prop] = propvalue;
				}
			});
			return arr;
		}
		return arr;
	}
};

export default arraytool;

let { LocalStream, MediaStreamFactory, StreamSourceInfo } = IRtc.Base;

export function isJSON(str) {
	if (typeof str == 'string') {
		try {
			var obj = JSON.parse(str);
			if (typeof obj == 'object' && obj) {
				return true;
			} else {
				return false;
			}
		} catch (e) {
			console.log('error：' + str + '!!!' + e);
			return false;
		}
	}
	console.log('It is not a string!');
}

export function dateStr() {
	var nowDate = new Date();
	var h = nowDate.getHours();
	var m = nowDate.getMinutes();
	var s = nowDate.getSeconds();
	var dateF = {
		year: nowDate.getFullYear(),
		month: nowDate.getMonth() + 1,
		date: nowDate.getDate(),
		h: h,
		m: m < 10 ? '0' + m : m,
		s: s < 10 ? '0' + s : s
	};
	return dateF.year + '/' + dateF.month + '/' + dateF.date + ' ' + dateF.h + ':' + dateF.m + ':' + dateF.s;
}

/*createlocalstream*/
export function createlocalstream(isvideo, isaudio, resolutionoption) {
	let audio = isaudio
		? {
				deviceId: undefined, //Do not provide deviceId if source is not "mic".
				source: 'mic' //Values could be "mic", "screen-cast", "file" or "mixed".
		  }
		: undefined;

	let resolution = resolutionoption;
	let video = isvideo
		? {
				resolution: resolution, //The Resolution defines the size of a rectangle.
				frameRate: 15,
				deviceId: undefined, //Do not provide deviceId if source is not "camera".
				source: 'camera' //values could be "camera", "screen-cast", "file" or "mixed".
		  }
		: undefined;

	let videoSource = isvideo ? 'camera' : undefined; //Video source info. Accepted values are: "camera", "screen-cast", "file", "mixed" or undefined.
	let audioSource = isaudio ? 'mic' : undefined; //Audio source info. Accepted values are: "mic", "screen-cast", "file", "mixed" or undefined.
	let streamSourceInfo = new StreamSourceInfo(audioSource, videoSource);

	let mediaStreamDeviceConstraints = {
		audio: audio,
		video: video
	};
	console.log('media、stream constraints', mediaStreamDeviceConstraints);
	return MediaStreamFactory.createMediaStream(mediaStreamDeviceConstraints)
		.then(function(mediaStream) {
			console.log(mediaStream);
			return new LocalStream(mediaStream, streamSourceInfo, { type: 'customer' });
		})
		.catch(function(error) {
			console.log(error);
			return Promise.reject(error);
		})
		.then(function(localstream) {
			console.log(localstream);
			return localstream;
		})
		.catch(function(error) {
			console.log(error);
			return Promise.reject(error);
		});
}

export function createmediaStream(isvideo, isaudio, resolutionoption) {
	let audio = isaudio
		? {
				deviceId: undefined, //Do not provide deviceId if source is not "mic".
				source: 'mic' //Values could be "mic", "screen-cast", "file" or "mixed".
		  }
		: undefined;

	let resolution = resolutionoption;
	let video = isvideo
		? {
				resolution: resolution, //The Resolution defines the size of a rectangle.
				frameRate: 15,
				deviceId: undefined, //Do not provide deviceId if source is not "camera".
				source: 'camera' //values could be "camera", "screen-cast", "file" or "mixed".
		  }
		: undefined;

	let videoSource = isvideo ? 'camera' : undefined; //Video source info. Accepted values are: "camera", "screen-cast", "file", "mixed" or undefined.
	let audioSource = isaudio ? 'mic' : undefined; //Audio source info. Accepted values are: "mic", "screen-cast", "file", "mixed" or undefined.
	let streamSourceInfo = new StreamSourceInfo(audioSource, videoSource);

	let mediaStreamDeviceConstraints = {
		audio: audio,
		video: video
	};
	return MediaStreamFactory.createMediaStream(mediaStreamDeviceConstraints)
		.then(function(mediaStream) {
			console.log(mediaStream);
			return new LocalStream(mediaStream, streamSourceInfo, { type: 'customer' });
		})
		.catch(function(error) {
			console.log(error);
			alert('create media stream failed' + error);
			return Promise.reject();
		})
		.then(function(localstream) {
			console.log(localstream);
			return localstream;
		})
		.catch(function(error) {
			console.log(error);
			alert('create local stream failed' + error);
		});
}

export function createscreenstream() {
	let audio = {
		deviceId: undefined, //Do not provide deviceId if source is not "mic".
		source: 'screen-cast' //Values could be "mic", "screen-cast", "file" or "mixed".
	};
	let resolution = {
		width: 1080,
		height: 720
	};
	let video =
		//= undefined
		{
			resolution: resolution, //The Resolution defines the size of a rectangle.
			frameRate: undefined,
			deviceId: undefined, //Do not provide deviceId if source is not "camera".
			source: 'screen-cast' //values could be "camera", "screen-cast", "file" or "mixed".
		};

	let videoSource = 'screen-cast'; //Video source info. Accepted values are: "camera", "screen-cast", "file", "mixed" or undefined.
	let audioSource = 'screen-cast'; //Audio source info. Accepted values are: "mic", "screen-cast", "file", "mixed" or undefined.
	let streamSourceInfo = new StreamSourceInfo(audioSource, videoSource);

	let extensionId = 'kaigeejmpfbncokkedpenhjhfpfcghbf';

	let mediaStreamDeviceConstraints = {
		audio: audio,
		video: video,
		extensionId: extensionId //The ID of Chrome screen sharing extension.
	};
	return MediaStreamFactory.createMediaStream(mediaStreamDeviceConstraints)
		.then(function(mediaStream) {
			console.log(mediaStream);
			return new LocalStream(mediaStream, streamSourceInfo, { type: 'screen' });
		})
		.catch(function(error) {
			console.log(error);
			return Promise.reject();
		})
		.then(function(localstream) {
			console.log(localstream.source.video);
			console.log(localstream.source.audio);
			return localstream;
		})
		.catch(function(error) {
			console.log(error);
		});
}

export function publishlocalstream(client, stream, option) {
	return client
		.publish(stream, option)
		.then(function(publication) {
			console.log('publish local success');
			console.log(publication);
			return publication;
		})
		.catch(function(error) {
			console.log('publish local stream failed: ', error);
			console.log(option);
			return Promise.reject(error);
		});
}

// export function publishscreenstream(client,stream,option) {
//   return client.publish(stream,option).then(function (publication) {
//     console.log("publish screen stream success")
//     console.log(publication);
//     return publication;
//   }).catch(function (error) {
//     console.log('publish screen stream failed: ', error);
//   })
// }

export function stopTrack(medias) {
	setTimeout(() => {
		medias.getTracks().forEach(track => {
			track.stop();
			console.log('关闭摄像头成功', new Date());
		});
	}, 200);
}

export function formatDuring(timeStamp) {
	let hours = parseInt((timeStamp % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
	let minutes = parseInt((timeStamp % (1000 * 60 * 60)) / (1000 * 60));
	let seconds = parseInt((timeStamp % (1000 * 60)) / 1000);
	hours = hours < 10 ? '0' + hours : hours;
	minutes = minutes < 10 ? '0' + minutes : minutes;
	seconds = seconds < 10 ? '0' + seconds : seconds;
	return hours + ':' + minutes + ':' + seconds;
}

//分割字符串
//例:
//str: scanCode_1
//key:'_'
//originStr:scancode
//replaceStr:推送扫码
//return: 推送扫码1
export const subStringAndReplaceName = (str, key, originStr, replaceStr) => {
	let index = str.indexOf(key);
	if (index != -1) {
		let Number = str.substr(index + 1, str.length - index - 1);
		if (originStr === str.substr(0, index)) {
			return replaceStr + Number;
		} else {
			return str;
		}
	} else {
		return str;
	}
};
